<template>
  <div>
    <h1>WebSocket 示例</h1>
    <!-- 输入框，用于输入要发送的消息 -->
    <input v-model="newMessage" placeholder="输入要发送的消息">
    <!-- 按钮，点击触发发送消息的操作 -->
    <button @click="sendMessage">发送消息</button>
    <ul>
      <!-- 显示接收到的消息 -->
      <li v-for="(message, index) in messages" :key="index">{{ message }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data () {
    return {
      messages: [], // 存储接收到的消息
      newMessage: '', // 存储用户输入的消息
      socket: null, // 创建 WebSocket 实例
      userId: '123', // 假设 userId 是从某个地方获取的，比如组件的 props 或者全局状态
      reconnectAttempts: 0, // 重连尝试次数
      MAX_RECONNECT_ATTEMPTS: 5, // 最大重连次数
      RECONNECT_INTERVAL: 5000 // 重连间隔时间（毫秒）
    }
  },
  mounted () {
    console.log('组件加载websocket调用')
    this.connectWebSocket()
  },
  beforeDestroy () {
    if (this.socket) {
      this.socket.close()
    }
  },
  methods: {
    connectWebSocket () {
      const url = 'ws://localhost:3005/ws1'
      this.socket = new WebSocket(url)

      this.socket.onopen = () => {
        console.log('WebSocket 连接已建立')
        this.reconnectAttempts = 0
      }

      this.socket.onmessage = (event) => {
        this.messages.push(event.data)
      }

      this.socket.onclose = () => {
        console.log('WebSocket 连接已关闭')
        if (this.reconnectAttempts < this.MAX_RECONNECT_ATTEMPTS) {
          setTimeout(() => {
            console.log('尝试重新连接...')
            this.reconnectAttempts++
            this.connectWebSocket()
          }, this.RECONNECT_INTERVAL)
        } else {
          console.log('达到最大重连次数，停止尝试')
        }
      }

      this.socket.onerror = (error) => {
        console.error('WebSocket 连接出错:', error)
        this.socket.close()
      }
    },
    sendMessage () {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
        // 获取用户输入的消息
        const message = this.newMessage
        if (message) {
          console.log(message)
          // 发送消息
          this.socket.send(JSON.stringify(message))
          // 清空输入框
          this.newMessage = ''
        }
      }
    }
  }
}
</script>

<style scoped></style>
